import * as qiniu from 'qiniu-js';
import api from '@/../public/api.js';
// 获取token前缀
let prefix = process.env.NODE_ENV === 'development' ? '/webapi/28080' : api.apiOther;

/**
 * 生成GUID
 */
function generateGUID() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    let r = (Math.random() * 16) | 0,
      v = c === 'x' ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
}

/**
 * 七牛云上传文件
 * @param file 文件对象
 * @param progress 上传进度回调
 * @returns {Promise<{hash:string; key:string}>}
 */
export async function qiniuUploadFile(file, subpath, progress) {
  return new Promise(async (resolve, reject) => {
    let res = await fetch(`${prefix}/token`, {
      method: 'GET',
    });
    let token = (await res.json()).token;

    // 去除文件后缀
    let suffix = file.name.split('.').pop();
    let path = subpath + '/' + generateGUID() + '.' + suffix;

    const observable = qiniu.upload(file, path, token);
    observable.subscribe({
      next(res) {
        progress && progress(res);
      },
      error(err) {
        reject(err);
      },
      complete(res) {
        res.key = 'http://img.zgcart.cn/' + res.key;

        resolve(res);
      },
    });
  });
}
